package cn.darkhorse.admin.controller.basic;

import cn.darkhorse.basic.domain.QmsProcessors;
import cn.darkhorse.basic.service.IQmsProcessorsService;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.AddressUtil;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.domain.SysRegion;
import com.ruoyi.system.service.SysRegionService;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

/**
 * 加工企业管理Controller
 *
 * @author ytq
 * @date 2024-07-18
 */
@RestController
@RequestMapping("/basic/processors")
public class QmsProcessorsController extends BaseController
{
    @Resource
    private IQmsProcessorsService qmsProcessorsService;
    @Resource
    private SysRegionService regionService;
    /**
     * 查询加工企业管理列表
     */
@ApiOperation("查询加工企业管理列表")
    @GetMapping("/list")
    public TableDataInfo list(QmsProcessors qmsProcessors)
    {
        startPage();
        List<QmsProcessors> list = qmsProcessorsService.selectQmsProcessorsList(qmsProcessors);
        return getDataTable(list);
    }


    /**
     * 获取加工企业管理详细信息
     */
    @ApiOperation("获取加工企业管理详细信息")
    @GetMapping(value = "/view")
    public AjaxResult view( Long id)
    {
        return success(qmsProcessorsService.selectQmsProcessorsById(id));
    }

    /**
     * 新增加工企业管理
     */
    @ApiOperation("新增加工企业管理")
    @Log(title = "加工企业管理", businessType = BusinessType.INSERT)
    @PostMapping(value = "save")
    public AjaxResult add(@RequestBody QmsProcessors qmsProcessors)
    {
        return toAjax(qmsProcessorsService.saveQmsProcessors(qmsProcessors));
    }

    /**
     * 删除加工企业管理
     */
    @ApiOperation("删除加工企业管理")
    @Log(title = "加工企业管理", businessType = BusinessType.DELETE)
	@PostMapping("/delete")
    public AjaxResult delete(@RequestBody Long id)
    {
        return toAjax(qmsProcessorsService.deleteQmsProcessorsById(id));
    }


    /**
     * 批量删除加工企业管理
     */
            @ApiOperation("批量删除加工企业管理")
    @Log(title = "加工企业管理", businessType = BusinessType.DELETE)
    @PostMapping("/deleteBatch")
    public AjaxResult deleteBatch(@RequestBody Long[] ids)
    {
        return toAjax(qmsProcessorsService.deleteQmsProcessorsByIds(ids));
    }

    /**
     * 导出加工企业管理列表
     */
            @ApiOperation("导出加工企业管理列表")
    @Log(title = "加工企业管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, QmsProcessors qmsProcessors)
    {
        List<QmsProcessors> list = qmsProcessorsService.selectQmsProcessorsList(qmsProcessors);
        ExcelUtil<QmsProcessors> util = new ExcelUtil<QmsProcessors>(QmsProcessors.class);
        util.exportExcel(response, list, "加工企业管理数据");
    }

    /**
     * 导入加工企业管理列表
     */
    @ApiOperation("导入加工企业管理列表")
    @Log(title = "加工企业管理", businessType = BusinessType.IMPORT)
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file) throws Exception
    {
        ExcelUtil<QmsProcessors> util = new ExcelUtil<QmsProcessors>(QmsProcessors.class);
        List<QmsProcessors> qmsProcessorsList = util.importExcel(file.getInputStream());
        if (StringUtils.isNull(qmsProcessorsList) || qmsProcessorsList.size() == 0)
        {
            throw new ServiceException("导入数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        StringBuilder appendMsg = new StringBuilder();
        for (QmsProcessors qmsProcessors : qmsProcessorsList)
        {
            String fullAddress = qmsProcessors.getFullAddress();
            Map<String, String> resolution = AddressUtil.addressResolution(fullAddress);
            if (!resolution.isEmpty()){
                String province = resolution.get("province");
                if (!province.isEmpty()){
                    System.out.println("省：" + province);
                    List<SysRegion> regions = regionService.lambdaQuery().like(SysRegion::getName, province).eq(SysRegion::getLevel, 1).list();
                    if (!regions.isEmpty()){
                        qmsProcessors.setProvince(String.valueOf(regions.get(0).getCode()));
                    }
                }
                String city = resolution.get("city");
                if (!city.isEmpty()){
                    System.out.println("市：" + city);
                    List<SysRegion> regions = regionService.lambdaQuery().like(SysRegion::getName, city).eq(SysRegion::getLevel, 2).list();
                    if (!regions.isEmpty()){
                        if (regions.get(0).getLevel()==2) {
                            qmsProcessors.setCity(String.valueOf(regions.get(0).getCode()));
                        }
                    }
                }
                String county = resolution.get("county");
                if (!county.isEmpty()){
                    System.out.println("区县：" + county);
                    List<SysRegion> regions = regionService.lambdaQuery().like(SysRegion::getName, county).eq(SysRegion::getLevel, 3).list();
                    if (!regions.isEmpty()){
                        qmsProcessors.setCounty(String.valueOf(regions.get(0).getCode()));
                    }
                }
                String address = resolution.get("address");
                qmsProcessors.setDetailedAddress(address);
            }else {
                appendMsg.append("<br/> 企业名称: "+qmsProcessors.getEnterpriseName() + " 企业地址: "+fullAddress + " 省市区解析失败");
            }
            try
            {
                if ( qmsProcessorsService.saveQmsProcessors(qmsProcessors)){
                    successNum++;
                }
            }
            catch (Exception e)
            {
                failureNum++;
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条");
        }
        if (appendMsg.length() > 0){
            successMsg.append("<br/>以下数据的部分字段导入失败：");
            successMsg.append(appendMsg);
        }
        return success(successMsg);
    }

    /**
     * 下载模板
     */
    @ApiOperation("下载模板")
    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response)
    {
        ExcelUtil<QmsProcessors> util = new ExcelUtil<QmsProcessors>(QmsProcessors.class);
        util.importTemplateExcel(response, "加工企业管理数据");
    }
}
